import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import { Table, Button, Tooltip } from 'antd';
import styles from './index.less';
import CreateUserModel from './createUser';
import UserRoleModel from './setUserRole';
import { getCenterEllipsis } from 'enoad-component-web/dist/src/core/util';
import { forEach, find, cloneDeep } from 'lodash';
/**
 * 用户管理界面。这里可以进行用户的新建、编辑、删除。可以给用户分配角色
 * 列表展示数据库中所有用户。账户和密码都会进行展示。
 * @param props
 * @returns
 */
const User = (props: any) => {
  const { dispatch, loading, dataSource } = props;

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [createUser, setCreateUser] = useState(false); //新建用户的弹窗model。
  const [editUser, setEditUser] = useState({}); //新建用户的弹窗model。

  const [visitSetRole, setVisitSetRole] = useState(false); //设置角色model

  const columns = [
    {
      title: '用户名',
      dataIndex: 'name',
      render: (_, item) => {
        return (
          <div
            onClick={() => {
              //编辑该用户
              openEditUser(item);
            }}
          >
            <Tooltip title={item.name}>
              {getCenterEllipsis(item.name, 10, 6, 6)}
            </Tooltip>
          </div>
        );
      },
    },
    {
      title: '密码',
      dataIndex: 'password',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '角色',
      dataIndex: 'role',
      render: (_, item) => {
        let role = item.role;
        if (role) {
          role = JSON.parse(role);
          return (
            <Tooltip title={role.name}>
              {getCenterEllipsis(role.name, 10, 6, 6)}
            </Tooltip>
          );
        }
      },
    },
    {
      title: '部门',
      dataIndex: 'department',
      render: (_, item) => {
        let depart = item.department;
        if (depart) {
          depart = JSON.parse(depart);
          return (
            <Tooltip title={depart.name}>
              {getCenterEllipsis(depart.name, 10, 6, 6)}
            </Tooltip>
          );
        }
      },
    },
    {
      title: '手机号',
      dataIndex: 'tel',
    },
  ];

  const fetchUserData = () => {
    dispatch({ type: 'enoadRBAC/fetchUserData', payload: {} });
  };

  useEffect(() => {
    fetchUserData();
  }, []);

  const onSelectChange = (rowKeys) => {
    setSelectedRowKeys(rowKeys);
  };

  const openCreateUser = () => {
    setEditUser({});
    setCreateUser(true);
  };

  const openEditUser = (item) => {
    setEditUser(item);
    setCreateUser(true);
  };

  const setUserRole = () => {
    selectedRowKeys[0]
    let user = find(dataSource, (data) => {
      return data._id === selectedRowKeys[0];
    });
    setEditUser(user);
    setVisitSetRole(true);
  };

  const deleteUser = () => {
    dispatch({
      type: 'enoadRBAC/deleteUser',
      payload: { ids: selectedRowKeys },
    }).then((res) => {
      if (res) {
        setSelectedRowKeys([]);
        fetchUserData();
      }
    });
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;
  return (
    <>
      {hasSelected ? (
        <div className={styles.selectView}>
          <div>
            <span
              style={{
                fontSize: '16px',
                marginRight: '10px',
                fontWeight: 'bold',
              }}
            >
              {'用户信息'}
            </span>
            <span>{`已经选中${selectedRowKeys.length}项`}</span>
          </div>
          <div>
            <Button
              className={styles.buttonType}
              type="primary"
              onClick={setUserRole}
              loading={loading.effects['enoadRBAC/fetchUserData']}
            >
              {'设置角色'}
            </Button>
            <Button
              className={styles.buttonType}
              type="primary"
              onClick={deleteUser}
              loading={loading.effects['enoadRBAC/deleteUser']}
            >
              {'删除'}
            </Button>
          </div>
        </div>
      ) : (
        <div className={styles.selectView}>
          <span
            style={{
              fontSize: '16px',
              marginRight: '10px',
              fontWeight: 'bold',
            }}
          >
            {'用户信息'}
          </span>
          <div>
            <Button
              className={styles.buttonType}
              type="primary"
              onClick={openCreateUser}
              loading={loading.effects['enoadRBAC/fetchUserData']}
            >
              {'新建用户'}
            </Button>
          </div>
        </div>
      )}

      <Table
        loading={loading.effects['enoadRBAC/fetchUserData']}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={dataSource}
      />
      {createUser && (
        <CreateUserModel
          createUser={createUser}
          setCreateUser={setCreateUser}
          fetchUserData={fetchUserData}
          user={editUser}
        />
      )}
      {visitSetRole && (
        <UserRoleModel
          visitSetRole={visitSetRole}
          setVisitSetRole={setVisitSetRole}
          fetchUserData={fetchUserData}
          user={editUser}
        />
      )}
    </>
  );
};
//关联到用户权限管理state的models中。
export default connect(({ enoadRBAC, loading }) => ({
  ...enoadRBAC,
  loading,
}))(User);
